#include <tsin/library/DynamicCounter.hpp>

#include <tsin/util/Logger.hpp>

#include <cstring>

using namespace tsin;

DynamicCounter::DynamicCounter()
        : current(0.0f),
          start(0.0f), step(0.0f), end(0.0f)
{
}

void DynamicCounter::init(float start, float end,
                          float step)
{
        if ((start < end && step < 0) ||
            (start > end && step > 0))
                step = -step;
        this->start = start;
        this->step = step;
        this->end = end;

        current = this->start;
}

void DynamicCounter::reinit()
{
        float arg1 = arguments[0]->getFloat();
        float arg2 = arguments[1]->getFloat();
        float arg3 = arguments[2]->getFloat();

        switch(nrArguments) {
        case 2:
                if (strcmp(desp, "NN") == 0)
                        init(arg1, arg2, 1.0f);
                break;
        case 3:
                if (strcmp(desp, "NNN") == 0)
                        init(arg1, arg3, arg2);
                break;
        }
}

DynamicEvent DynamicCounter::postTick(void *, void *)
{
        DynamicEvent ret = EVENT_NONE;
        if ((step > 0 && current >= end) ||
            (step < 0 && current <= end)) {
                current = end;
                ret |= EVENT_END;
        } else {
                current += step;
                ret |= EVENT_REINIT;
        }
        return ret;
}

char DynamicCounter::getDescriptor()
{
        return 'N';
}

int DynamicCounter::getInt()
{
        return static_cast<int>(current);
}

float DynamicCounter::getFloat()
{
        return current;
}

extern "C" LIBRARY_DLLEXPORT DynamicObject *bindCounter()
{
        return new DynamicCounter;
}
